package com.fjsh.web;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.fjsh.base.bean.GatewayRouteDefinition;
import com.fjsh.entity.AppRoute;
import com.fjsh.service.AppRouteService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping(value = "/route")
public class AppRouteController {
    @Autowired
    private AppRouteService appRouteService;

    @GetMapping(value = "list")
    public List<AppRoute> list() {

        return appRouteService.findAll();
    }

    /*  参数示例 filters：parts表示几级映射
        {
            "filters":[{
                "name":"StripPrefix",
                "args":{"parts":1}
            }],
            "routeId":"com-fjsh-resource-activiti",
            "uri":"lb://com-fjsh-resource-activiti",
            "order":1,
            "predicates":[{
                "name":"Path",
                "args":{"pattern":"/activiti/**"}
            }]
        }
     */
    @PostMapping(value = "/add")
    public String save(@RequestBody GatewayRouteDefinition gatewayRouteDefinition) {

        if (StrUtil.isBlank(gatewayRouteDefinition.getRouteId())) {
            return "id不能为空";
        } else if (StrUtil.isBlank(gatewayRouteDefinition.getUri())) {
            return "uri不能为空";
        }

        AppRoute route = new AppRoute();
        route.setRouteId(gatewayRouteDefinition.getRouteId());
        route.setUri(gatewayRouteDefinition.getUri());
        route.setOrder(gatewayRouteDefinition.getOrder());
        route.setPredicates(gatewayRouteDefinition.getPredicates() != null ? JSON.toJSONString(gatewayRouteDefinition.getPredicates()) : null);
        route.setFilters(gatewayRouteDefinition.getFilters() != null ? JSON.toJSONString(gatewayRouteDefinition.getFilters()) : null);

        boolean res = appRouteService.saveOrUpdate(route);
        return res ? "操作成功" : "操作失败";
    }

    @DeleteMapping(value = "{routeId}")
    public String delete(@PathVariable("routeId") String routeId) {
        AppRoute route = appRouteService.findByRouteId(routeId);
        if (route == null || StringUtils.isBlank(route.getRouteId())) {
            return "路由不存在";
        }

        boolean res = appRouteService.delete(route);
        return res ? "操作成功" : "操作失败";
    }
}